<?php
// $Id$

/**
 * Controller_Column 控制器
 */
class Controller_Column extends Controller_Abstract
{
    function actionIndex()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();

        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $select = Column::find('enterprise_id = ?', $cur_user->enterprise_id)->order('column_sequence ASC')->all();;

        $select->limitPage($page, 10);
        // 将分页信息和查询到的数据传递到视图
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['collums'] = $select->getAll();

        $this->_view['num'] = $select->getCount();
        $this->_viewname = 'index';
    }

    function actioninsert()
    {
        // 为 $this->_view 指定的值将会传递数据到视图中
        # $this->_view['text'] = 'Hello!';
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();

        $select = Column::find('enterprise_id = ?', $cur_user->enterprise_id)->order('column_sequence ASC')->all();
        
        $this->_view['col_count'] = $select->getCount();
        $this->_viewname = 'insert';
    }

    function actionAdd()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();

        if(isset($_POST['channelname']))
        {
            $channelnames = $_POST['channelname'];//这里取得POST过来的文本框的数目
            //for($i=1011;$i<=($num+1011);$i++)
            foreach($channelnames as $value)
            { 
                if($value != "")
                {
                    $column = new Column();
                    $column->column_name = $value;
                    $column->enterprise_id = $cur_user->enterprise_id;
                    $column->save();
                }
            }  
            return $this->_redirectMessage(
                '提示您:',
                '栏目添加成功',
                url('column/index'));
        }
    }

    function actionDelete()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $user = $this->_app->currentUserObject();
        //if(3 != $user->permission_id)
        //{
        //	return $this->_redirect(url('column/index'));
        //}
        if(isset($_POST['checkboxid'])){
            $id=$_POST['checkboxid'];

            foreach ($id as $value){
                //$column = Column::find('column_id  = ?', $value)->query();
                //$column->column_hide_status=1;
                Column::meta()->destroyWhere('column_id = ?', $value);
                //删除栏目相关的文章
            }
        }

        return $this->_redirect(url('column/index'));
    }

    function actionEdit()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        //$cur_user = $this->_app->currentUserObject();
        $col = Column::find('column_id = ?', $this->_context->column_id)->query();

        if($col->id() != $this->_context->column_id)
        {
            return $this->_redirect(url('column/index'));
        }

        if(isset($_POST['column_title']))
        {
            $col->column_name =$_POST['column_title'];
            $col->column_desc =$_POST['column_desc'];
            $col->column_sequence=$_POST['column_seqence'];
            if(isset($_POST['column_hide_or_not']))
            {
                $col->column_status=$_POST['column_hide_or_not'];
            }
            if(isset($_POST['upload_pic']))
            {
                $web_site=Q::ini('appini/web_site_ip');
                $col->column_logo = $web_site. $_POST['upload_pic'];
            }

            $col->save();
            return $this->_redirectMessage(
                '提示您:',
                '编辑成功',
                url('column/index'));
        }

        $this->_view['col'] = $col;
        $this->_viewname = 'edit';
    }

    function actionUploadedimage()
    {
        if(null == $this->_app->currentUser())
        {
            echo "err";
        }
        else
        {
            $error = "";
            $msg = "";
            $error_code=0;
            $fileElementName = 'fileToUpload';
            if(!empty($_FILES[$fileElementName]['error']))
            {
                switch($_FILES[$fileElementName]['error'])
                {
                case '0':
                    $error_code = 101;
                    break;
                case '1':
                    $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    $error_code = 102;
                    break;
                case '2':
                    $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    $error_code = 102;
                    break;
                case '3':
                    $error = 'The uploaded file was only partially uploaded';
                    $error_code = 102;
                    break;
                case '4':
                    $error = 'No file was uploaded.';
                    $error_code = 102;
                    break;

                case '6':
                    $error = 'Missing a temporary folder';
                    $error_code = 102;
                    break;
                case '7':
                    $error = 'Failed to write file to disk';
                    $error_code = 102;
                    break;
                case '8':
                    $error = 'File upload stopped by extension';
                    $error_code = 102;
                    break;
                case '999':
                default:
                    $error = 'No error code avaiable';
                }
            }
            elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
            {
                $error_code=102;
            }
            else 
            {
                $msg .= " File Name: " . $_FILES['fileToUpload']['name'] . ", ";
                $msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name']);
            }		
            if($error_code == 102)
            {
                echo "{";
                echo				"error: '" . $error . "',\n";
                echo				"error_code: '" . $error_code . "',\n";
                echo "}";
                return;
            }
            $col = Column::find('column_id = ?', $this->_context->column_id)->query();

            if($col->id() != $this->_context->column_id)
            {
                echo "{";
                echo				"error: '" . $error . "',\n";
                echo				"error_code: '" . $error_code . "',\n";
                echo "}";
                return;
            }

            $time = time();
            $uploader = new Helper_Uploader();
            $file = $uploader->file($fileElementName);
            if($file->isSuccessed())
            {
                try{
                    if($file->isValid('jpg, jpeg, png, gif'))
                    {
                        $filepath = $this->_app->config('ROOT_DIR'). '/img/column_log/' . date('Ym');
                        //echo "file:".$filepath;
                        $url_path = $this->_context->baseDir().'img/column_log/' . date('Ym');

                        if(!file_exists($filepath))
                        {
                            mkdir($filepath);
                        }
                        if(file_exists($filepath.'/'.$time.$file->filename()))
                        {
                            unlink ( $filepath.'/'.$time.$file->filename() );
                        }

                        $image = Helper_Image::createFromFile($file->filepath(), $file->extname());
                        $w = Q::ini('appini/column_logo_width');
                        $h = Q::ini('appini/column_logo_height');

                        $image->crop($w, $h);
                        $image->saveAsJpeg($filepath.'/'.$time.$file->filename());
                        $dst_file = $filepath.'/'.$time.$file->filename();

                        $image->destroy();
                        $file->unlink();

                        if(strlen($col->column_logo ) > 0)
                        {							
                            $old_pic = $col->column_logo;

                            if(file_exists($old_pic))
                            {
                                unlink($old_pic);
                            }
                            else
                            {
                                $old_pic .="oooo";
                            }
                        }

                        if(strlen($dst_file) > 0 && file_exists($dst_file))
                        {	
                            //echo "dst_file:".$dst_file;
                            $col->column_logo  = $url_path.'/'.$time.$file->filename();
                        }
                        else
                        {
                            $col->column_logo  = null;
                        }
                        $col->save();
                        $error_code = 100;

                        $retVal = "{success:'".$col->column_logo ."'}";
                        echo $retVal;
                        return;
                    }
                    else 
                    {
                        $error='uploaded err';
                        $error_code = 105;
                    }
                }
                catch (Exception $ex)
                {				
                    $error='uploaded err';
                    $error_code = 103;
                }
                return;
            }
            echo "{";
            echo				"error: '" . $error . "',\n";
            echo				"error_code: '" . $error_code . "',\n";
            echo "}";
            return;
        }
    }

    function actiondispalycolumn()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('column/index'));
        }
        if(!isset($this->_context->column_id))
        {
            return $this->_redirect(url('column/index'));
        }

        $select = Article::find('column_id = ?', $this->_context->column_id)->order('article_id DESC')->all();
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $column = Column::find('column_id = ?', $this->_context->column_id)->query();       
        $article_per_page = Q::ini('appini/web_page_count');
        $select->limitPage($page, $article_per_page);

        $this->_view['pagination'] = $select->getPagination();
        $this->_view['articles'] = $select->getAll();
        $this->_view['column'] = $column;
        $this->_view['permission_id'] = $this->_app->currentUserObject()->permission_id; 
        $this->_view['num'] = $select->getCount() > $article_per_page ? $article_per_page : $select->getCount();
        $this->_viewname = 'dispalycolumn';
    }

    function actionRequire()
    {
        require 'genrss.php';

        $web_site=Q::ini('appini/web_site_ip');
        //$web_site.=$this->_context->baseDir();
        if(!isset($this->_context->column_id))
        {
            $date = Date('Y-m-d H:i:s', time()); 
            $rss_gen=new RSS('test', "http://www.baidu.com", '测试数据这里', '');
            $rss_gen->AddItem("我和你", 
                "http://www.baidu.com", "你需要什么", $date, $web_site.$this->_context->baseDir().'static/test/00.jpg');
            $rss_gen->AddItem("我和你", 
                "http://www.baidu.com", "你需要什么", $date, $web_site.$this->_context->baseDir().'static/test/00.jpg');
            $ret=$rss_gen->Fetch();
            echo $ret;
            return;
        }
        else
        {
            $select = Article::find('column_id = ? and article_status = 4', $this->_context->column_id)->order('article_id DESC')->all();
            $page = intval($this->_context->page);
            if ($page < 1) $page = 1;
            $column = Column::find('column_id = ?', $this->_context->column_id)->query();;

            $select->limitPage($page, Q::ini('appini/web_page_count'));

            $articles = $select->getAll();
            $date = Date('Y-m-d H:i:s', time()); 

            $web_site=Q::ini('appini/web_site_ip');

            $col_img="...";
            if(strlen($column->column_logo) > 0)
            {
                $col_img=$web_site.$column->column_logo;
            }

            $rss_gen=new RSS($column->column_name, $col_img, $select->getCount(), '');
            foreach($articles as $artic)
            { 
                $rss_gen->AddItem($artic->article_name, $web_site.$artic->article_url, 
                    $artic->article_summary, $date, $artic->article_icon);
            }
            $ret=$rss_gen->Fetch();
            echo $ret;
            return;
        }
    }	

    function actionRequireAllColumn()
    {
        require 'genrss.php';
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $cur_user = $this->_app->currentUserObject();
        $rss_gen=new RSS('电信', "http://www.baidu.com", '测试数据这里', '');

        $date = Date('Y-m-d H:i:s', time()); 
        $columns = Column::find('enterprise_id = ?', $cur_user->enterprise_id)->order('column_sequence ASC')->all()->getAll();
        $web_site=Q::ini('appini/web_site_ip');
        foreach($columns as $col)
        {
            //$column_site = $web_site;
            //$column_site .= 'index.php?controller=column&amp;action=require&amp;column_id='.$col->column_id;
            $column_id=$col->column_id;
            if(strlen($col->column_logo)> 3)
            {
                $rss_gen->AddItem($col->column_name, $column_id, $web_site.$col->column_logo, $date, 'null');//$col->column_sequence
            }
            else
            {
                $rss_gen->AddItem($col->column_name, $column_id, 'null', $date, 'null');
            }
        }
        return $rss_gen->Display();
    }
}


